package com.zl.tesseract.scanner.view;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Point;
import android.graphics.Rect;
import android.os.Handler;
import android.os.Message;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.widget.RelativeLayout;

import com.zl.tesseract.R;
import com.zl.tesseract.scanner.utils.ScreenUtils;

public final class ScannerFinderView extends RelativeLayout {

    private static final int[] SCANNER_ALPHA = {0, 64, 128, 192, 255, 192, 128, 64};
    private static final long ANIMATION_DELAY = 100L;
    private static final int OPAQUE = 0xFF;

    private static final int viewSetDp = 180;// ******************************XML中设置的取景框的高dp值，

    private static Point ScrRes;

    private Paint mPaint;
    private int mScannerAlpha;
    private int mMaskColor;// 面具颜色
    private int mFrameColor;// 四个边的颜色
    private int mLaserColor;// 激光线的颜色
    private int mAngleColor;// 四个角的颜色
    private int mTextColor;// 文本颜色
    private int mFocusThick;// 四个边的厚度
    private int mAngleThick;// 四个角的粗线的厚度
    private int mAngleLength;// 四个角的粗线的长度

    private Rect mFrameRect; //绘制的Rect
    private Rect mRect; //返回的Rect

    public ScannerFinderView(Context context) {
        this(context, null);
    }

    public ScannerFinderView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public ScannerFinderView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        mPaint = new Paint();
        mPaint.setAntiAlias(true);
        Resources resources = getResources();
        mMaskColor = resources.getColor(R.color.finder_mask);
        mFrameColor = resources.getColor(R.color.finder_frame);
        mLaserColor = resources.getColor(R.color.finder_laser);
        mAngleColor = resources.getColor(R.color.finder_angle);
        mTextColor = resources.getColor(R.color.finder_text);

        mFocusThick = 1;
        mAngleThick = 6;
        mAngleLength = 40;// 40
        mScannerAlpha = 0;
        init(context);

    }

    public void init(Context context) {
        if (isInEditMode()) {
            return;
        }
        // 需要调用下面的方法才会执行onDraw方法
        setWillNotDraw(false);

        if (mFrameRect == null) {
            ScrRes = ScreenUtils.getScreenResolution(context);
            int width = ScrRes.x;

//            mFrameRect = new Rect(left, top, left + width, top + height);
//            mFrameRect = new Rect(left + 50, top, left + width - 50, top + height);// 默认的框是宽占满屏幕的，现在左右隔开50的距离
            int viewHeight = ScreenUtils.dip2px(context, viewSetDp);
            mFrameRect = new Rect(50, 30, width - 50, viewHeight-30);// 默认的框是宽占满屏幕的，现在左右隔开50的距离
            mRect = mFrameRect;
        }
    }

    /**
     * 设置为扫手机号样式，缩小取景框
     */
    public void setScanPhoneMode(Context context) {
        ScrRes = ScreenUtils.getScreenResolution(context);
        int width = ScrRes.x;

        int viewHeight = ScreenUtils.dip2px(context, viewSetDp);
        mFrameRect = new Rect(100, 110, width - 100, viewHeight-110);
        mRect = mFrameRect;

        this.invalidate();
    }

    /**
     * 设置为扫条形码样式，还原取景框
     */
    public void setScanCodeMode(Context context) {
        ScrRes = ScreenUtils.getScreenResolution(context);
        int width = ScrRes.x;

        int viewHeight = ScreenUtils.dip2px(context, viewSetDp);
        mFrameRect = new Rect(50, 30, width - 50, viewHeight-30);// 默认的框是宽占满屏幕的，现在左右隔开50的距离
        mRect = mFrameRect;

        this.invalidate();
    }


    public Rect getRect() {
        return mRect;
    }

    @Override
    public void onDraw(Canvas canvas) {
        if (isInEditMode()) {
            return;
        }
        Rect frame = mFrameRect;
        if (frame == null) {
            return;
        }
        int width = canvas.getWidth();
        int height = canvas.getHeight();

        // 绘制焦点框外边的暗色背景
        mPaint.setColor(mMaskColor);
        canvas.drawRect(0, 0, width, frame.top, mPaint);
        canvas.drawRect(0, frame.top, frame.left, frame.bottom + 1, mPaint);
        canvas.drawRect(frame.right + 1, frame.top, width, frame.bottom + 1, mPaint);
        canvas.drawRect(0, frame.bottom + 1, width, height, mPaint);

        drawFocusRect(canvas, frame);
        drawAngle(canvas, frame);

        // 暂时不用激光线和文本了
//        drawText(canvas, frame);
//        drawLaser(canvas, frame);
    }

    /**
     * 画聚焦框，白色的
     *
     * @param canvas
     * @param rect
     */
    private void drawFocusRect(Canvas canvas, Rect rect) {
        // 绘制焦点框（黑色）
        mPaint.setColor(mFrameColor);
        // 上-绘制矩形的上面的边
        canvas.drawRect(rect.left + mAngleLength, rect.top, rect.right - mAngleLength, rect.top + mFocusThick, mPaint);
        // 左-绘制矩形的左边的边
        canvas.drawRect(rect.left, rect.top + mAngleLength, rect.left + mFocusThick, rect.bottom - mAngleLength,
                mPaint);
        // 右-绘制矩形的右边的边
        canvas.drawRect(rect.right - mFocusThick, rect.top + mAngleLength, rect.right, rect.bottom - mAngleLength,
                mPaint);
        // 下-绘制矩形的下边的边
        canvas.drawRect(rect.left + mAngleLength, rect.bottom - mFocusThick, rect.right - mAngleLength, rect.bottom,
                mPaint);
    }

    /**
     * 画四个角
     *
     * @param canvas
     * @param rect
     */
    private void drawAngle(Canvas canvas, Rect rect) {
        mPaint.setColor(mAngleColor);
        mPaint.setAlpha(OPAQUE);
        mPaint.setStyle(Paint.Style.FILL);
        mPaint.setStrokeWidth(mAngleThick);
        int left = rect.left;
        int top = rect.top;
        int right = rect.right;
        int bottom = rect.bottom;
        // 左上角
        canvas.drawRect(left, top, left + mAngleLength, top + mAngleThick, mPaint);
        canvas.drawRect(left, top, left + mAngleThick, top + mAngleLength, mPaint);
        // 右上角
        canvas.drawRect(right - mAngleLength, top, right, top + mAngleThick, mPaint);
        canvas.drawRect(right - mAngleThick, top, right, top + mAngleLength, mPaint);
        // 左下角
        canvas.drawRect(left, bottom - mAngleLength, left + mAngleThick, bottom, mPaint);
        canvas.drawRect(left, bottom - mAngleThick, left + mAngleLength, bottom, mPaint);
        // 右下角
        canvas.drawRect(right - mAngleLength, bottom - mAngleThick, right, bottom, mPaint);
        canvas.drawRect(right - mAngleThick, bottom - mAngleLength, right, bottom, mPaint);
    }

    /**
     * 画文本
     *
     * @param canvas
     * @param rect
     */
    private void drawText(Canvas canvas, Rect rect) {
        int margin = 40;
        mPaint.setColor(mTextColor);
        mPaint.setTextSize(getResources().getDimension(R.dimen.text_size_13sp));
        String text = getResources().getString(R.string.auto_scan_notification);
        Paint.FontMetrics fontMetrics = mPaint.getFontMetrics();
        float fontTotalHeight = fontMetrics.bottom - fontMetrics.top;
        float offY = fontTotalHeight / 2 - fontMetrics.bottom;
        float newY = rect.bottom + margin + offY;
        float left = (ScreenUtils.getScreenWidth() - mPaint.getTextSize() * text.length()) / 2;

        // 重新绘制文字，绘制到中间激光线的上面
        int middle = rect.height() / 2 + rect.top;
        canvas.drawText(text, left, middle - 10, mPaint);
//        canvas.drawText(text, left, newY, mPaint);
    }

    /**
     * 画激光线
     *
     * @param canvas
     * @param rect
     */
    private void drawLaser(Canvas canvas, Rect rect) {
        // 绘制焦点框内固定的一条扫描线
        mPaint.setColor(mLaserColor);
        mPaint.setAlpha(SCANNER_ALPHA[mScannerAlpha]);
        mScannerAlpha = (mScannerAlpha + 1) % SCANNER_ALPHA.length;
        int middle = rect.height() / 2 + rect.top;
        canvas.drawRect(rect.left + 2, middle - 1, rect.right - 1, middle + 2, mPaint);

        mHandler.sendEmptyMessageDelayed(1, ANIMATION_DELAY);
    }

    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            invalidate();
        }
    };

    @Override
    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        mHandler.removeMessages(1);
    }
}
